﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace RMS.Common
{
    public class EncryptionManager
    {
        private const string defaultKey = "rms"; //默认密钥  

        public static string DES(string text, string key = defaultKey)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.UTF8.GetBytes(text);
                des.Key = GetKey(key);
                des.IV = des.Key;
                des.Mode = CipherMode.ECB;
                des.Padding = PaddingMode.PKCS7;
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(inputByteArray, 0, inputByteArray.Length);
                        cs.FlushFinalBlock();
                        StringBuilder ret = new StringBuilder();
                        foreach (byte b in ms.ToArray())
                        {
                            ret.AppendFormat("{0:x2}", b);
                        }
                        return ret.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        private static byte[] GetKey(string strKey = defaultKey)
        {
            byte[] arrBTmp = Encoding.UTF8.GetBytes(strKey);
            // 创建一个空的8位字节数组（默认值为0）   
            byte[] arrB = new byte[8];
            // 将原始字节数组转换为8位   
            for (int i = 0; i < arrBTmp.Length && i < arrB.Length; i++)
            {
                arrB[i] = arrBTmp[i];
            }
            return arrB;
        }
    }
}
